// import AccreditIcon from '@/components/accreditDia/AccreditIcon'
import { AssistantIcon } from '@/components/bs-icons/assistant'
import { cname } from '@/components/bs-ui/utils'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
// import { AddToIcon } from '../../bs-icons/addTo'
import { Func } from '@/permissions/constants'
import { useFuncsStore } from '@/store/funcStore'
import { DelIcon } from '../../bs-icons/del'
import { GoIcon } from '../../bs-icons/go'
import { PlusIcon } from '../../bs-icons/plus'
import { SettingIcon } from '../../bs-icons/setting'
import { SkillIcon } from '../../bs-icons/skill'
import { UserIcon } from '../../bs-icons/user'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '../../bs-ui/card'
import { Switch } from '../../bs-ui/switch'
import './styles.css'
import { Tooltip } from 'antd'

interface IProps<T> {
  data: T
  /** id为''时，表示新建 */
  id?: number | string
  type: 'skill' | 'sheet' | 'assist' | 'setting' // 技能列表｜侧边弹窗列表
  title: string
  edit?: boolean
  description: React.ReactNode | string
  checked?: boolean
  user?: string
  isAdmin?: boolean
  headSelecter?: React.ReactNode
  footer?: React.ReactNode
  icon?: any
  logo?: string
  onClick?: () => void
  onSwitchClick?: () => void
  onAddTemp?: (data: T) => void
  onCheckedChange?: (b: boolean, data: T) => Promise<any>
  onDelete?: (data: T) => void
  onSetting?: (data: T) => void
  onAccreditDia?: () => void
}

export const gradients = ['bg-amber-500', 'bg-orange-600', 'bg-teal-500', 'bg-purple-600', 'bg-blue-700']

// 'bg-slate-600',
// 'bg-amber-500',
// 'bg-red-600',
// 'bg-orange-600',
// 'bg-teal-500',
// 'bg-purple-600',
// 'bg-blue-700',
// 'bg-yellow-600',
// 'bg-emerald-600',
// 'bg-green-700',
// 'bg-cyan-600',
// 'bg-sky-600',
// 'bg-indigo-600',
// 'bg-violet-600',
// 'bg-purple-600',
// 'bg-fuchsia-700',
// 'bg-pink-600',
// 'bg-rose-600'
export function TitleIconBg({ id, className = '', children = <SkillIcon /> }) {
  return (
    <div
      className={cname(
        `flex items-center justify-center rounded-sm ${gradients[parseInt(id + '', 16) % gradients.length]}`,
        className
      )}
    >
      {children}
    </div>
  )
}

function CardComponent<T>(
  {
    id = '',
    data,
    type,
    icon: Icon = SkillIcon,
    logo,
    edit = false,
    user,
    title,
    checked,
    isAdmin,
    description,
    footer = null,
    headSelecter = null,
    onClick,
    onSwitchClick,
    onDelete,
    onAddTemp,
    onCheckedChange,
    onSetting,
    onAccreditDia
  }: IProps<T>,
  _ref
) {
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()

  const [_checked, setChecked] = useState(checked)

  const { t } = useTranslation()

  const handleCheckedChange = async bln => {
    console.log(bln)
    if (bln) {
      if (!hasFuncPermission([Func.assistant.online])) {
        return
      }
    } else {
      if (!hasFuncPermission([Func.assistant.offline])) {
        return
      }
    }
    const res = await onCheckedChange(bln, data)
    if (res === false) return
    setChecked(bln)
  }

  // 新建小卡片（sheet）
  if (!id && type === 'sheet') {
    return (
      <Card
        className="group w-[320px] cursor-pointer border-dashed border-[#BEC6D6] bg-background-new transition hover:border-primary hover:shadow-none"
        onClick={onClick}
      >
        <CardHeader>
          <div className="flex justify-between pb-2">
            <PlusIcon className="transition-none group-hover:text-primary" />
          </div>
          <CardTitle className="">{title}</CardTitle>
        </CardHeader>
        <CardContent className="h-0 overflow-auto p-2 scrollbar-hide">
          <CardDescription className="cardDescri">{description}</CardDescription>
        </CardContent>
        <CardFooter className="flex h-10 justify-end">
          <div className="cursor-pointer rounded">
            <GoIcon className="transition-none group-hover:text-primary" />
          </div>
        </CardFooter>
      </Card>
    )
  }

  // 新建卡片
  if (!id) {
    return (
      <Card
        className=" application_card group cursor-pointer border-dashed border-[#BEC6D6] transition hover:border-primary hover:shadow-none"
        onClick={onClick}
        style={{ backgroundColor: '#F5F7FB' }}
      >
        <CardHeader className="flexRow">
          <div className="flex justify-between">
            {/* <PlusIcon className="transition-none group-hover:text-primary" /> */}
            <svg width="72" height="72" viewBox="0 0 72 72" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect y="18.7017" width="42" height="54" rx="8" transform="rotate(-21.953 0 18.7017)" fill="#D6D9FF" />
              <rect x="17.571" y="8.89307" width="42" height="54" rx="8" fill="url(#paint0_linear_4810_820)" />
              <rect x="26.571" y="23.8931" width="24" height="4" rx="2" fill="white" />
              <rect x="26.571" y="33.8931" width="24" height="4" rx="2" fill="white" />
              <rect x="26.571" y="43.8931" width="12" height="4" rx="2" fill="white" />
              <circle cx="59" cy="52" r="11" fill="black" />
              <rect x="54" y="51" width="10" height="2" rx="1" fill="white" />
              <rect x="58" y="57" width="10" height="2" rx="1" transform="rotate(-90 58 57)" fill="white" />
              <defs>
                <linearGradient
                  id="paint0_linear_4810_820"
                  x1="17.571"
                  y1="35.8931"
                  x2="59.571"
                  y2="35.8931"
                  gradientUnits="userSpaceOnUse"
                >
                  <stop stopColor="#3B74FB" />
                  <stop offset="0.505" stopColor="#6468F7" />
                  <stop offset="1" stopColor="#9659F2" />
                </linearGradient>
              </defs>
            </svg>
          </div>
          <CardTitle>{title}</CardTitle>
        </CardHeader>
        <CardContent className="application_card_cont h-[140px] overflow-auto scrollbar-hide">
          <CardDescription className="cardDescri">{description}</CardDescription>
        </CardContent>
        {/* <CardFooter className="flex h-10 justify-end" style={{ background: '#F5F7FB' }}>
          <div className="cursor-pointer rounded">
            <GoIcon className="transition-none group-hover:text-primary" />
          </div>
        </CardFooter> */}
      </Card>
    )
  }

  // 侧边弹窗列表（sheet）
  if (type === 'sheet') {
    return (
      <Card
        className="group relative w-[320px] cursor-pointer bg-[#F7F9FC] hover:bg-[#EDEFF6] hover:shadow-none"
        onClick={onClick}
      >
        <CardHeader className="pb-2">
          <CardTitle className="truncate-doubleline">
            <div className="flex items-center gap-2 pb-2">
              <TitleIconBg id={id}>
                <Icon />
              </TitleIconBg>
              <p className=" align-middle">{title}</p>
            </div>
            {/* <span></span> */}
          </CardTitle>
        </CardHeader>
        <CardContent className="mb-2 h-fit max-h-[60px] overflow-auto scrollbar-hide">
          <CardDescription className="cardDescri break-all">{description}</CardDescription>
        </CardContent>
        <CardFooter className=" block">{footer}</CardFooter>
      </Card>
    )
  }

  // 技能组件
  return (
    <Card
      className="application_card group cursor-pointer bg-background-Assistant hover:bg-background-hoverAssistant"
      onClick={() => edit && onClick()}
    >
      <CardHeader>
        <div className="flex justify-between pb-2">
          <TitleIconBg id={id}>
            {logo ? (
              <img className="card_icon_application" key={id} width={24} height={24} src={logo} />
            ) : type === 'skill' ? (
              <SkillIcon className="card_icon_application" />
            ) : (
              <AssistantIcon className="card_icon_application" />
            )}
          </TitleIconBg>
          <div className="flex items-center gap-1">
            {headSelecter}
            <Switch
              style={{ background: 'red !important' }}
              checked={_checked}
              className="w-12"
              // eslint-disable-next-line @typescript-eslint/ban-ts-comment
              // @ts-expect-error
              texts={[t('skills.online'), t('skills.offline')]}
              onCheckedChange={b => edit && handleCheckedChange(b)}
              onClick={e => {
                e.stopPropagation()
                onSwitchClick?.()
              }}
            ></Switch>
          </div>
        </div>
        <CardTitle className="domOverflowEllip cardTitle_span">{title}</CardTitle>
      </CardHeader>
      {/* <CardContent className="h-[120px] overflow-auto scrollbar-hide"> */}
      <CardContent className="h-[120px] scrollbar-hide">
        <CardDescription className="cardDescri domOverflowEllip_thr break-all" style={{ WebkitLineClamp: 5 }}>
          {description || t('application.contEmpty')}
        </CardDescription>
      </CardContent>
      <CardFooter className="flex h-10 justify-between" style={{ marginTop: '20px' }}>
        <div className="flex max-w-[calc(100%-60px)] items-center gap-1">
          <UserIcon />
          <span style={{ minWidth: '58px' }} className="cardFouter_span_title text-sm text-muted-foreground">
            {t('skills.createdBy')}
          </span>
          <span className="text-sm font-medium" style={{ lineHeight: '20px', maxWidth: '160px', wordBreak: 'break-all' }}>
            {user}
          </span>
        </div>
        {edit && (
          <div className="hidden group-hover:flex">
            {/* 授权 */}
            {/* {
              <div
                className="cursor-pointer rounded hover:bg-[#EAEDF3]"
                onClick={e => {
                  e.stopPropagation()
                  onAccreditDia()
                }}
              >
                <AccreditIcon />
              </div>
            } */}
            {/* !checked && 编辑 */}
            {
              <div
                className="cursor-pointer rounded hover:bg-[#EAEDF3]"
                onClick={e => {
                  e.stopPropagation()
                  onSetting(data)
                }}
              >
                <SettingIcon />
              </div>
            }
            {/* {isAdmin && type === 'skill' && (
              <div
                className="cursor-pointer rounded hover:bg-[#EAEDF3]"
                onClick={e => {
                  e.stopPropagation()
                  onAddTemp(data)
                }}
              >
                <AddToIcon />
              </div>
            )} */}
            <div
              className="cursor-pointer rounded hover:bg-[#EAEDF3]"
              onClick={e => {
                e.stopPropagation()
                onDelete(data)
              }}
            >
              <DelIcon />
            </div>
          </div>
        )}
      </CardFooter>
    </Card>
  )
}

function fixedForwardRef<T, P = {}>(
  render: (props: P, ref: React.Ref<T>) => React.ReactNode
): (props: P & React.RefAttributes<T>) => React.ReactNode {
  return React.forwardRef(render) as any
}

export default fixedForwardRef(CardComponent)
